<template>
  <ul class="todo-main">
    <li v-for="todo in todoList" :key="todo.id">
      <label>
        <input
          type="checkbox"
          :checked="todo.does"
          @click="change($event, todo.id)"
        />
        <input
          v-show="!todo.isEdit"
          v-model="todo.todo"
          @blur="handleBlur($event, todo)"
          ref="inputBlur"
        />
        <span v-show="todo.isEdit">{{ todo.todo }}</span>
      </label>
      <button class="btn btn-danger" @click="deleteRow(todo.id)">删除</button>
      <button class="btn btn-warning" @click="handEdit(todo)">编辑</button>
    </li>
  </ul>
</template>

<script>
import PubSub from "pubsub-js";
export default {
  name: "TodoItem", //这里必须为字符串
  data() {
    return {};
  },
  methods: {
    change($event, id) {
      let does = $event.target.checked;
      console.log("$event :>> ", does);
      console.log("$event :>> ", id);
      PubSub.publish("changeChecked", { id, does });
    },
    deleteRow(id) {
      if (confirm("请确定要删除已经完成的任务")) {
      }
      PubSub.publish("handDelete", id);
    },
    handEdit(todo) {
      if (todo.hasOwnProperty("isEdit")) {
        console.log("有 isEdit");
        todo.isEdit = false;
      } else {
        console.log("没有 isEdit");
        //vm.$set( target, propertyName/index, value )
        this.$set(todo, "isEdit", false);
      }
      let arr = this.$refs.inputBlur;
      console.log(arr[0]._value);
      this.$nextTick(() => {
        arr.forEach((item, index) => {
          if (item._value == todo.todo) {
            this.$refs.inputBlur[index].focus();
          }
        });
      });
    },
    handleBlur(e, todo) {
      todo.isEdit = true;
      if (!e.target.value.trim()) {
        alert("输入不能为空");
        return;
      }
      todo.todo = e.target.value;
      PubSub.publish("updateToDo", todo);
    },
  },
  props: ["todoList"],
};
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
li:hover button {
  display: block;
}
.btn-warning {
  background-color: burlywood;
  margin-right: 5px;
}
</style>>